package com.sxt.service.impl;

import com.sxt.entity.SysUser;
import com.sxt.entity.SysUserRole;
import com.sxt.mapper.SysUserMapper;
import com.sxt.mapper.SysUserRoleMapper;
import com.sxt.service.SysUserService;
import com.sxt.utils.MD5HashUtils;

import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author liangtiandong
 * @since 2019-12-17
 */
@Service
@Slf4j // 	private static final Logger LOG = LoggerFactory.getLogger(SysUserServiceImpl.class);
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper ;

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper ;

	@Override
	public SysUser findUserByUsername(String username) {
		Assert.notNull(username, "用户名不能为null");
		log.info("使用用户名{}，查询用户",username); // {} 是占位符，后面的值会填进来
		// SysUser::getUsername 取到数据库的列名称
		return sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
	}

	@Override
	public IPage<SysUser> findByPage(Page<SysUser> page, SysUser sysUser) {
		log.info("分页查询{},{}", page.getCurrent(),page.getSize());
		//select * from sys_user where limit n,s;
		IPage<SysUser> pageData = sysUserMapper.selectPage(page, new LambdaQueryWrapper<SysUser>().
				// 		StringUtils.hasText(sysUser.getUsername() 是否拼接like的条件
				like(StringUtils.hasText(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername())
				);

		return pageData;
	}

	@Override
	public boolean save(SysUser entity) {
		Assert.notNull(entity, "新增用户对象不能为null");
		if(!StringUtils.hasText(entity.getUsername()) || !StringUtils.hasText(entity.getPassword())){
			throw new IllegalArgumentException("用户名和密码不能为空");
		}
		// 对用户的密码
		String oriPasssword = entity.getPassword();
		String hashedPassword = MD5HashUtils.toHex(oriPasssword, "whsxt", 2);
		entity.setPassword(hashedPassword);
		entity.setCreateTime(LocalDateTime.now()); // 设置创建时间
		boolean isSave = super.save(entity);//entity 就有id
		if(isSave) {
			List<Object> roleIdList = entity.getRoleIdList();
			// 需要写user_role 的中间表
			if(roleIdList!= null && !roleIdList.isEmpty()) {
				for (Object roleId : roleIdList) {
					SysUserRole sysUserRole = new SysUserRole();
					sysUserRole.setUserId(entity.getUserId());
					sysUserRole.setRoleId(Long.valueOf(roleId+""));
					sysUserRoleMapper.insert(sysUserRole);
				}
			}
		}
		return isSave ;
	}

	@Override
	public SysUser getById(Serializable id) {
		Assert.notNull(id, "id不能为空");
		log.info("查询id为:{}的用户",id);
		SysUser user = super.getById(id);
		if(user!=null) {// 查询该用户的角色信息
			List<Object> roleIds = sysUserRoleMapper.selectObjs(new LambdaQueryWrapper<SysUserRole>().
					select(SysUserRole::getRoleId).
					eq(SysUserRole::getUserId, id)
					);
			user.setRoleIdList(roleIds);
		}
		return  user ;
	}

	/**
	 * 修改用户
	 * 修改操作里面，用户的id 不能为null
	 */
	@Override
	public boolean updateById(SysUser entity) {
		Assert.notNull(entity, "修改的对象不能为null");
		if(entity.getUserId()==null || !StringUtils.hasText(entity.getUsername()) || !StringUtils.hasText(entity.getPassword())) {
			throw new IllegalArgumentException("修改的user对象参数错误");
		}
		String hashedPassword = MD5HashUtils.toHex(entity.getPassword(), "whsxt", 2);
		entity.setPassword(hashedPassword) ;
		boolean isUpdate = super.updateById(entity);
		if(isUpdate) { // 修改中间表
			//1 先删除
			sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, entity.getUserId()));
			// 2 在新增
			List<Object> roleIdList = entity.getRoleIdList();
			if(roleIdList !=null && !roleIdList.isEmpty()) {
				for (Object roleIdObj : roleIdList) {
					SysUserRole sysUserRole = new SysUserRole();
					sysUserRole.setUserId(entity.getUserId());
					sysUserRole.setRoleId(Long.valueOf(roleIdObj+""));
					sysUserRoleMapper.insert(sysUserRole) ;
				}
			}
		}

		return isUpdate;
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
	     if(idList ==null || idList.isEmpty()) {
	    	 throw new RuntimeException("要删除的数据为null");
	     }
	     log.info("本次删除的数据为{}",idList);
	     boolean isOk = super.removeByIds(idList);
	     if(isOk) {
	    	 sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, idList));
	     }
		return isOk;
	}
}
